package com.thinkTank.oa.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.entity.ConfOfAttr;
import com.thinkTank.oa.entity.Conference;
import com.thinkTank.oa.entity.Customer;
import com.thinkTank.oa.entity.Demand;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Project;
import com.thinkTank.oa.lucene.IsolrOperation;
import com.thinkTank.oa.lucene.LucenePerson;
import com.thinkTank.oa.lucene.SolrOperation;
import com.thinkTank.oa.service.ConOfAttrService;
import com.thinkTank.oa.service.ConferenceService;
import com.thinkTank.oa.service.CustomerService;
import com.thinkTank.oa.service.DictiontryService;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.service.ProjectService;
import com.thinkTank.oa.util.ExcelUtil;
import com.thinkTank.oa.util.FileUtils;
import com.thinkTank.oa.util.StrUtil;

@SuppressWarnings("unused")
@Controller
@RequestMapping("/confofattr")
public class ConfofattrController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(ConfofattrController.class);

	@Resource
	private ConOfAttrService conOfAttrService;

	@Resource
	private DictiontryService dictiontryService;

	@Resource
	private PersonService personService;

	@Resource
	private ConferenceService conferenceService;

	@Resource
	private ProjectService projectService;

	@Resource
	private CustomerService customerService;

	/** 将常用的list封装到Model中 */
	private void addListToModel(Model model) {
		/**
		 * 用于修改页面的回显
		 */
		// 项目来源
		List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所属领域
		List<Dictiontry> researchFieldDictiontryList = getResearchField();
		// 专家类型
		List<Dictiontry> personTypeList = getPersonType();
		// 人才级别
		List<Dictiontry> talentLevelListByDic = getTalentLevel();
		// 获取客户类型
		List<Dictiontry> customerTypeList = getCustomerType();
		// 客户性质
		List<Dictiontry> customerNatureList = getCustomerNature();
		// 项目类型
		List<Dictiontry> projectTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTTYPE);

		/**
		 * 用于专家添加页面中的遍历
		 */
		
		// 专家来源
		List<Dictiontry> sourceList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTSOURCE);
		// 专家类型
		List<Dictiontry> typeList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PERSONTYPE);
		// 所属领域
		List<Dictiontry> fieldList =SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDFIELD);
		// 人才级别
		List<Dictiontry> talentLevelList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_TALENTLEVEL);
		/**
		 * 用于显示对接详情添加页面的遍历
		 */
		// 对接状态下拉列表
		List<Dictiontry> buttStatus = getButtStatus();
		// 所有国家
		List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
		model.addAttribute("countryDictiontryList", countryDictiontryList);
		model.addAttribute("projectTypeDictiontryList", projectTypeDictiontryList);

		model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
		model.addAttribute("personTypeList", personTypeList);
		model.addAttribute("customerTypeList", customerTypeList);
		model.addAttribute("customerNatureList", customerNatureList);
		model.addAttribute("talentLevelListByDic", talentLevelListByDic);
		model.addAttribute("sourceList", sourceList);
		model.addAttribute("typeList", typeList);
		model.addAttribute("fieldList", fieldList);
		model.addAttribute("talentLevelList", talentLevelList);
		model.addAttribute("buttStatus", buttStatus);
	}

	@RequestMapping(value = "/conferencePerson")
	public String conferencePerson(Integer pageNum, @RequestParam("pid") String pid, HttpServletRequest request) {

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);

		// 根据当前会议id查询到中间表中关联的嘉宾信息
		List<ConfOfAttr> attrList = conOfAttrService.findAttrPersonByConfId(pid);


		List<String> conferenceNameList = new ArrayList<String>();

		for (int i = 0; i < attrList.size(); i++) {
			Person person = personService.getById(attrList.get(i).getPersonId());
			if (person != null) {
				attrList.get(i).setPersonName(person.getName());
				Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
				attrList.get(i).setConferenceName(conf.getConferenceName());
			}
		}
		
		
		Collections.sort(attrList, new Comparator<ConfOfAttr>() {
            public int compare(ConfOfAttr o1, ConfOfAttr o2) {
                return Collator.getInstance(Locale.CHINESE).compare(o1.getPersonName(),o2.getPersonName());
            }
        });

		// 将list放进PageInfo
		PageInfo<ConfOfAttr> pageInfo = new PageInfo<ConfOfAttr>(attrList);

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("pid", pid);
		return "confoattrlist";
	}

	/**
	 * 删除演讲嘉宾方法
	 * 
	 * @param conferencePid
	 * @param person
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteConferenceGuest", method = RequestMethod.GET)
	public String deleteConferenceGuest(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("personPid") String personPid, Person person, BindingResult bindingResult,
			HttpServletRequest request) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setPersonId(personPid);

		conOfAttrService.deleteAttrByPersonId(attr);
		return conferencePerson(null, conferencePid, request);
	}
	
	
	/**
	 * 会议详细页面删除演讲嘉宾方法
	 * 
	 * @param conferencePid
	 * @param person
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteConferenceGuestForDetail", method = RequestMethod.GET)
	public String deleteConferenceGuestForDetail(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("personPid") String personPid, Person person, BindingResult bindingResult,
			HttpServletRequest request) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setPersonId(personPid);

		conOfAttrService.deleteAttrByPersonId(attr);
		return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
	}

	/**
	 * 修改会议客户方法 xyx
	 * 
	 * @param pid
	 * @param request
	 * @return 2018年8月21日
	 */
	@RequestMapping(value = "/conferenceProject")
	public String conferenceProject(Integer pageNum, @RequestParam("pid") String pid, Model model) {

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}

		// 根据当前会议id查询到中间表中关联的项目信息
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		List<ConfOfAttr> attrList = conOfAttrService.findAttrProjectByConfId(pid);
		List<String> conferenceNameList = new ArrayList<String>();

		for (int i = 0; i < attrList.size(); i++) {
			Project project = projectService.getById(attrList.get(i).getProjectId());

			// set项目名称
			attrList.get(i).setProjectName(project.getProjectName());

			Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
			// set项会议名称
			attrList.get(i).setConferenceName(conf.getConferenceName());
		}

		// 将list放进PageInfo
		PageInfo<ConfOfAttr> pageInfo = new PageInfo<ConfOfAttr>(attrList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);

		model.addAttribute("conferenceId", pid);
		model.addAttribute("pid", pid);
		return "confoattrprojectlist";
	}

	/**
	 * 会议活动添加项目id跳转页面
	 * 
	 * @param pid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addProject")
	public String addProject(@RequestParam("pid") String pid, Model model,
			@RequestParam(defaultValue = "1") int pageNo) {
		model.addAttribute("conferenceId", pid);

		pageInfo(model, pageNo, new Project(),pid);

//		PageInfo<Project> pageInfo = new PageInfo<Project>(new ArrayList<>());
		addListToModel(model);
//		model.addAttribute(pageInfo);

		return "ConferenceAddProject";
	}

	private void pageInfo(Model model, int pageNo, Project pro, String conferenceId) {

		// 项目状态
		List<Dictiontry> projectStatusDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTSTATUS);
		// 项目类型
		List<Dictiontry> projectTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTTYPE);

		List<ConfOfAttr> ofattrList = conOfAttrService.queryAllAndProjectNoIn(conferenceId);
		String[] attayStr = new String[ofattrList.size()];
		for (int i = 0; i < ofattrList.size(); i++) {
			attayStr[i] = ofattrList.get(i).getProjectId();
		}

		pro.setNotInCustomerIds(attayStr);

		PageHelper.startPage(pageNo, 10);
		List<Project> list = projectService.queryAll(pro);
		list.forEach(project -> project
				.setProjectType(getDictiontryWorth(project.getProjectType(), projectTypeDictiontryList)));
		list.forEach(project -> project.setProjectStatusWorth(
				projectStatusDictiontryList.stream().filter(psd -> psd.getPid().equals(project.getProjectStatus()))
						.map(Dictiontry::getWorth).findAny().orElse("")));

		PageInfo<Project> pageInfo = new PageInfo<Project>(list);
		addListToModel(model);
		model.addAttribute(pageInfo);
	}

	/**
	 * 删除会议项目方法
	 * 
	 * @param conferencePid
	 * @param person
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteConferenceProject", method = RequestMethod.GET)
	public String deleteConferenceProject(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("projectId") String projectId, Model model) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setProjectId(projectId);

		conOfAttrService.deleteAttrByProjectId(attr);
		return conferenceProject(null, conferencePid, model);
	}
	
	@RequestMapping(value = "/deleteConferenceProjectForDetail", method = RequestMethod.GET)
	public String deleteConferenceProjectForDetail(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("projectId") String projectId, Model model) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setProjectId(projectId);

		conOfAttrService.deleteAttrByProjectId(attr);
		return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
	}

	/**
	 * 修改会议客户方法 xyx
	 * 
	 * @param pid
	 * @param request
	 * @return 2018年8月21日
	 */
	@RequestMapping(value = "/conferenceCustomer")
	public String conferenceCustomer(Integer pageNum, @RequestParam("pid") String pid, Model model) {

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}

		Conference conference = conferenceService.getById(pid);

		// 根据当前会议id查询到中间表中关联的项目信息
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		List<ConfOfAttr> attrList = conOfAttrService.findAttrCustomerByConfId(pid);
		List<String> conferenceNameList = new ArrayList<String>();

		for (int i = 0; i < attrList.size(); i++) {
			Customer customer = customerService.getById(attrList.get(i).getCustomerId());

			// set项目名称
			attrList.get(i).setCustomerName(customer.getCustomerName());

			Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
			// set项会议名称
			attrList.get(i).setConferenceName(conf.getConferenceName());
		}

		// 将list放进PageInfo
		PageInfo<ConfOfAttr> pageInfo = new PageInfo<ConfOfAttr>(attrList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("conferenceId", pid);
		model.addAttribute("conference", conference);
		return "confoattrcustomerlist";
	}

	/**
	 * 删除会议客户方法
	 * 
	 * @param conferencePid
	 * @param person
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteConferenceCustomer", method = RequestMethod.GET)
	public String deleteConferenceCustomer(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("customerId") String customerId, Model model) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setCustomerId(customerId);

		conOfAttrService.deleteAttrByCustomerId(attr);
		return conferenceCustomer(null, conferencePid, model);
	}
	
	@RequestMapping(value = "/deleteConferenceCustomerForDetail", method = RequestMethod.GET)
	public String deleteConferenceCustomerForDetail(@RequestParam("conferencePid") String conferencePid,
			@RequestParam("customerId") String customerId, Model model) {

		ConfOfAttr attr = new ConfOfAttr();
		attr.setConferenceId(conferencePid);
		attr.setCustomerId(customerId);

		conOfAttrService.deleteAttrByCustomerId(attr);
		return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
	}

	/**
	 * 会议活动添加客户id跳转页面
	 * 
	 * @param pid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addCustomer")
	public String addCustomer(@RequestParam("conferenceId") String conferenceId, Customer customer,
			BindingResult bindingResult, Integer pageNum, Model model,
			@RequestParam(value = "customerNumberId", required = false) String customerNumberId) {

		model.addAttribute("conferenceId", conferenceId);
		addListToModel(model);

//		if (StrUtil.isEmpty(customer) && StringUtil.isEmpty(customerNumberId)) {
//			// 将list放进PageInfo
//			PageInfo<Customer> pageInfo = new PageInfo<Customer>(new ArrayList<>());
//			// 传至前台页面展示
//			model.addAttribute("pageInfo", pageInfo);
//
//			return "conferenceAddCustomer";
//		}

		String cityId = "";
		String province = "";

		if (StringUtil.isNotEmpty(customer.getArea())) {
			areaModel(model, customer.getArea(), customer.getDomesticOrForeign());
		}

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		addListToModel(model);
		String customerNum = "";
		if (StringUtil.isNotEmpty(customer.getMajorNeeds())) {
			customer.setMajorNeeds(customer.getMajorNeeds().trim());
		}

		if (StringUtil.isNotEmpty(customer.getCustomerName())) {
			customer.setCustomerName(customer.getCustomerName().trim());
		}
		// 重新复制客户id
		if (StringUtil.isNotEmpty(customerNumberId)) {
			customerNum = String.valueOf(customerNumberId.trim());
			// 去除字母
			customerNum = customerNum.replaceAll("[a-zA-Z]", "");
		}

		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(customer.getResearchField())) {
			researchFieldArr = customer.getResearchField().split(",");
			customer.setResearchFieldNumber(researchFieldArr.length);
			customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));
		}
		model.addAttribute("researchFieldArr", researchFieldArr);
		if (StringUtil.isNotEmpty(customerNum)) {
			customer.setCustomerNumber(Integer.parseInt(customerNum));
		}

		// 查询所有会议活动数据
		List<ConfOfAttr> ofattrList = conOfAttrService.queryAllAndCustomerNoIn(conferenceId);
		String[] attayStr = new String[ofattrList.size()];
		for (int i = 0; i < ofattrList.size(); i++) {
			attayStr[i] = ofattrList.get(i).getCustomerId();
		}

		customer.setNotInCustomerIds(attayStr);
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		List<Customer> customerList = customerService.queryNotInCustomer(customer);

		for (int i = 0; i < customerList.size(); i++) {
			String areaStr = "";
			String reachName = "";
			// 得到所属领域二进制
			String rearch = customerList.get(i).getResearchField();
			// 得到areaId
			String areaStrId = String.valueOf(customerList.get(i).getArea());
			if (areaStrId != null && !"".equals(areaStrId) && !"null".equals(areaStrId)) {
				if (areaStrId.length() < 10 && areaStrId.length() > 5 && areaStrId.length() != 4) {
					// 说明是区的id
					// 截取得到省和市的id
//					Dictiontry dicArea = new Dictiontry();
//					dicArea.setNames(areaStrId);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
//					// 区的名字
//					areaStr = dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					cityId = areaStrId.substring(0, 5);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
//					dicArea.setNames(cityId);
//					// 市的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					province = areaStrId.substring(0, 2);
//					dicArea.setNames(province);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 0);
				}

				if (areaStrId.length() == 4) {
					// 说明是国外的
					Dictiontry dicArea = new Dictiontry();
					dicArea.setPid(Integer.parseInt(areaStrId));
					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 1);
				}
				if (areaStrId.length() < 6 && areaStrId.length() > 2 && areaStrId.length() != 4) {
					// 说明是市的id
//					Dictiontry dicArea = new Dictiontry();
//					cityId = areaStrId.substring(0, 5);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
//					dicArea.setNames(cityId);
//					// 市的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					province = areaStrId.substring(0, 2);
//					dicArea.setNames(province);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 0);

				}

				if (areaStrId.length() < 3 && areaStrId.length() > 0 && areaStrId.length() != 4) {
					// 说明是省的id
					Dictiontry dicArea = new Dictiontry();
					province = areaStrId.substring(0, 2);
					dicArea.setNames(province);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 0);
				}
			}
			// 给地区附上名字
			customerList.get(i).setAreaNameStr(areaStr);
			// String rearchStr = StrUtil.byteToString(rearch);
			reachName = getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
			customerList.get(i).setResearchFieldNameStr(reachName);
			// 取出当前客户性质
			int customerNatureStr = customerList.get(i).getCustomerNature();
			// 取出当前合作状态
			int currentStateStr = customerList.get(i).getCurrentState();
			customerList.get(i)
					.setCustomerNatureName(getDicSingleWorth(customerNatureStr, Constant.DICTIONTRY_CUSTOMERNATURE));
			customerList.get(i)
					.setCurrentStateName(getDicSingleWorth(currentStateStr, Constant.DICTIONTRY_CURRENTSATUS));
		}

		//
		// System.out.println(stringByByte("7,3,1,2,10,8"));
		//
		// System.out.println(byteToString("00000000001011000111"));

		// 将list放进PageInfo
		PageInfo<Customer> pageInfo = new PageInfo<Customer>(customerList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);

		return "conferenceAddCustomer";
	}

	/**
	 * 客户匹配项目，保存客户和项目的id xyx
	 * 
	 * @param pid
	 * @param model
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/conferenceAddCustomer", method = RequestMethod.GET)
	@ResponseBody
	public String conferenceAddCustomer(@RequestParam(value = "conferenceId", required = false) String conferenceId,
			@RequestParam(value = "checkStr", required = false) String checkStr, Model model,
			HttpServletRequest request) {

		String[] customerArry = checkStr.split(",");
		for (String customerId : customerArry) {
			// 客户存在,往中间表中插入一条数据
			ConfOfAttr ofattr = new ConfOfAttr();
			ofattr.setPid(StrUtil.getUUID32());
			ofattr.setConferenceId(conferenceId);
			ofattr.setCustomerId(customerId);
			conOfAttrService.add(ofattr);
		}
		return "success";
	}

	/**
	 * 客户匹配项目，保存客户和项目的id xyx
	 * 
	 * @param pid
	 * @param model
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/conferenceAddProject", method = RequestMethod.GET)
	@ResponseBody
	public String conferenceAddProject(@RequestParam(value = "conferenceId", required = false) String conferenceId,
			@RequestParam(value = "checkStr", required = false) String checkStr, Model model,
			HttpServletRequest request) {

		String[] projectArry = checkStr.split(",");
		for (String projectId : projectArry) {
			// 客户存在,往中间表中插入一条数据
			ConfOfAttr ofattr = new ConfOfAttr();
			ofattr.setPid(StrUtil.getUUID32());
			ofattr.setConferenceId(conferenceId);
			ofattr.setProjectId(projectId);
			conOfAttrService.add(ofattr);
		}
		return "success";
	}

	@RequestMapping("/showConditionQuery")
	public String showConditionQuery(@RequestParam("conferenceId") String conferenceId, Model model, Project project,
			String searchKeyword, @RequestParam(defaultValue = "1") int pageNo) {

		model.addAttribute("conferenceId", conferenceId);

		if (StrUtil.isEmpty(project) && StringUtil.isEmpty(searchKeyword)) {

			return addProject(conferenceId, model, pageNo);
		}

		if (StringUtil.isNotEmpty(searchKeyword)) {
			if (searchKeyword.matches("R\\d{6,}"))
				project.setProjectNumber(Integer.parseInt(searchKeyword.replaceFirst("R", "")));
			else
				project.setProjectName(searchKeyword);
		}
		String[] researchFieldArr = null;
		String[] projectTypedArr = null;
		if (StringUtil.isNotEmpty(project.getProjectType())) {
			projectTypedArr = project.getProjectType().split(",");
			project.setProjectTypeNumber(projectTypedArr.length);
			project.setProjectTypeInteger(StrUtil.stringByByte(project.getProjectType()));
		}
		if (StringUtil.isNotEmpty(project.getResearchField())) {
			researchFieldArr = project.getResearchField().split(",");
			project.setResearchFieldNumber(researchFieldArr.length);
			project.setResearchFieldInteger(StrUtil.stringByByte(project.getResearchField()));
		}
		model.addAttribute("searchKeyword", searchKeyword);
		model.addAttribute("project", project);
		model.addAttribute("researchFieldArr", researchFieldArr);
		model.addAttribute("projectTypedArr", projectTypedArr);
		if (project.getArea() != null && project.getDomesticOrForeign() != null)
			areaModel(model, project.getArea(), project.getDomesticOrForeign());
		pageInfo(model, pageNo, project, conferenceId);
		return "ConferenceAddProject";
	}

	/**
	 * 分页查询
	 * 
	 * @return 返回专家主页面
	 */
	@RequestMapping(value = "/addPerson", produces = "application/json;charset=UTF-8")
	public String addPerson(@RequestParam("conferenceId") String conferenceId, Integer pageNo, Person person,
			Model model, @RequestParam(value = "expertNumberId", required = false) String expertNumberId) {
		// 分页
		if (null == pageNo) {
			pageNo = 1;
		}

//		if (StrUtil.isEmpty(person) && StringUtil.isEmpty(expertNumberId)) {
//			// 将list放进PageInfo
//			PageInfo<Person> pageInfo = new PageInfo<Person>(new ArrayList<>());
//			addListToModel(model);
//			// 传至前台页面展示
//			model.addAttribute("pageInfo", pageInfo);
//			model.addAttribute("conferenceId", conferenceId);
//
//			return "conferenceAddperson";
//		}

		// 'E'+专家id来检索专家时，去除前缀操作
		String expertNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(expertNumberId)) {
			expertNum = String.valueOf(expertNumberId.trim());
			// 去除字母
			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(expertNum)) {
			person.setExpertNumber(Integer.parseInt(expertNum));
		}

		String[] researchFieldArr = null;
		String[] talentLevelArr = null;
		if (StringUtil.isNotEmpty(person.getTalentLevel())) {
			talentLevelArr = person.getTalentLevel().split(",");
			person.setTalentLevelNumber(talentLevelArr.length);
			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
		}
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
			person.setResearchFieldNumber(researchFieldArr.length);
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}

		// 人才级别
		List<Dictiontry> talentLevelListByDic = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_TALENTLEVEL);

		// 模糊查询person表
		List<ConfOfAttr> ofattrList = conOfAttrService.queryAllAndPersonNoIn(conferenceId);
		if (ofattrList != null && ofattrList.size() > 0) {
			String[] attayStr = new String[ofattrList.size()];
			for (int i = 0; i < ofattrList.size(); i++) {
				attayStr[i] = ofattrList.get(i).getPersonId();
			}
			person.setNotInCustomerIds(attayStr);
		}

		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
		List<Person> list = personService.findMPersonList(person);
		// 遍历人才级别、所属领域

		// 将list放进PageInfo
		PageInfo<Person> pageInfo = new PageInfo<Person>(list);

		// 因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
				.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));

		if (person.getArea() != null && person.getDomesticOrForeign() != null) {
			areaModel(model, person.getArea(), person.getDomesticOrForeign());
		}

		addListToModel(model);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("conferenceId", conferenceId);
		model.addAttribute("person", person);
		model.addAttribute("researchFieldArr", researchFieldArr);
		model.addAttribute("talentLevelArr", talentLevelArr);
		model.addAttribute("talentLevelListByDic", talentLevelListByDic);
		return "conferenceAddperson";
	}

	/**
	 * 客户添加嘉宾，保存客户和嘉宾的id xyx
	 * 
	 * @param pid
	 * @param model
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/conferenceAddPerson", method = RequestMethod.GET)
	@ResponseBody
	public String conferenceAddPerson(@RequestParam(value = "conferenceId", required = false) String conferenceId,
			@RequestParam(value = "checkStr", required = false) String checkStr, Model model,
			HttpServletRequest request) {

		String[] personArry = checkStr.split(",");
		for (String personId : personArry) {
			ConfOfAttr ofattr = new ConfOfAttr();
			ofattr.setPid(StrUtil.getUUID32());
			ofattr.setConferenceId(conferenceId);
			ofattr.setPersonId(personId);
			conOfAttrService.add(ofattr);
		}
		return "success";
	}
	
	
	/**
	 * 进入嘉宾添加页面
	 * @return
	 */
	@RequestMapping(value= "addNewPerson",produces="application/json;charset=UTF-8")
	public String addNewPerson(@RequestParam("conferencePid") String conferencePid,Model model){
		//将person传递给前台
		if(!model.containsAttribute("person")){
			model.addAttribute("person", new Person());
		}
		if (!model.containsAttribute("researchFieldArr")) {
			model.addAttribute("researchFieldArr", "");
		}
		if (!model.containsAttribute("talentLevelArr")) {
			model.addAttribute("talentLevelArr", "");
		}
		
		model.addAttribute("conferencePid", conferencePid);
				
		//调用本类方法
		addListToModel(model);
		return "conferenceaddnewperson";
	}
	
	
	
	/**
	 * 添加方法
	 * @param person 
	 * @return 专家的主页面
	 * @throws IOException 
	 */
	@RequestMapping(value= "addnewPerson",method = RequestMethod.POST)
	public String addnewPerson(@RequestParam("conferencePid") String conferencePid,@Valid Person person,BindingResult result,@RequestParam("annex1") MultipartFile annex1,
			HttpServletRequest request,Model model) throws Exception{
		
		//pid
		person.setPid(StrUtil.getUUID32());
		//收集人（录入人）
		person.setCollectPersonId(getUserInfoBySession(request).getUserId());
		//录入时间
		person.setEntryTime(StrUtil.getCurrentDateTime());
		//将所属领域复选框转换为二进制格式
		if(StringUtil.isNotEmpty(person.getResearchField())){
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		//将人才级别复选框转换为二进制格式
		if(StringUtil.isNotEmpty(person.getTalentLevel())){
			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
		}
		
		//上传附件
		if (!annex1.isEmpty() && annex1 != null) {
			// 文件名字
			String fileName = annex1.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("person", fileName);
			person.setAnnex(oldFileName);
			try {
				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}
		
		// 表单验证逻辑
		if (result.hasErrors()) {
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				//调用本类方法
				addInfo(person,model);
				
				//发生错误，直接return
				model.addAttribute("person", person);
				return addNewPerson(conferencePid,model);
			}
		}
		
		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
		if (!person.getName().isEmpty() && (!person.getTell().isEmpty() || !person.getFixedPhone().isEmpty() || 
			!person.getEmail().isEmpty() || !person.getWechat().isEmpty() || !person.getOtherContact().isEmpty())){
			//当数据库中可以通过姓名+任意一种联系方式查询出专家 就提示此人已存在
			Person per = personService.findPersonByInfo(person);
			if (per != null) {
				model.addAttribute("info", "此人已存在！");
				//调用本类方法
				addInfo(person,model);
				
				model.addAttribute("person", person);
				return addNewPerson(conferencePid,model);
			}
			personService.addPerson(person);
			
			//创建isolrOperation接口对象指向其实现类 
			IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
			//把Person转换为LucenePerson
			LucenePerson lucenePerson = lucenePersonConversion(person);
			List<LucenePerson> list = new ArrayList<LucenePerson>();
			list.add(lucenePerson);
			isolrOperation.add("person", list);
			
			conferenceAddPerson(conferencePid, person.getPid(), model, request);
		}else {
			model.addAttribute("alert", "请至少填写一种联系方式！");
			//调用本类方法
			addInfo(person,model);
			
			model.addAttribute("person", person);
			return addNewPerson(conferencePid,model);
		}
		
		return conferencePerson(null, conferencePid, request);
	}
	
	
	//提取添加页面回显的公共方法
	public void addInfo(Person person,Model model){
		// 获取地区相关数据，便于回显
		String areaId = person.getArea();
		String cityId = "";
		String province = "";
		if (StringUtil.isNotEmpty(areaId)) {
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
				// 说明是区的id
				// 截取得到省和市的id
				cityId = areaId.substring(0, 5);
				province = areaId.substring(0, 2);
				model.addAttribute("areaId", areaId);
				model.addAttribute("cityId", cityId);
				model.addAttribute("province", province);
			}
			if (areaId.length() < 3 && areaId.length() > 0) {
				// 说明是省的id
				model.addAttribute("province", areaId);
			}
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
				// 说明是市的id
				// 截取得到省和市的id
				cityId = areaId;
				province = areaId.substring(0, 2);
				model.addAttribute("province", province);
				model.addAttribute("cityId", cityId);
			}

			// 所有市
			List<Dictiontry> cityDictiontryList = getCityByProvince(province);
			// 所有区
			List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

			model.addAttribute("cityDictiontryList", cityDictiontryList);
			model.addAttribute("areaDictiontryList", areaDictiontryList);
		}

		//回显所属领域
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
		}
		if (researchFieldArr != null) {
			model.addAttribute("researchFieldArr", researchFieldArr);
		} else {
			model.addAttribute("researchFieldArr", "");
		}
		//回显人才级别
		String[] talentLevelArr = null;
		if (StringUtil.isNotEmpty(person.getTalentLevel())) {
			talentLevelArr = person.getTalentLevel().split(",");
		}
		if (talentLevelArr != null) {
			model.addAttribute("talentLevelArr", talentLevelArr);
		} else {
			model.addAttribute("talentLevelArr", "");
		}

		if(person.getDomesticOrForeign()!=null){
			//国内外和省市区、国家名都不能为空
			if (person.getDomesticOrForeign() == 1 && areaId != null) {
				model.addAttribute("countryId", Integer.parseInt(areaId));
			}
		}
		
	}
	
	@ResponseBody
	@RequestMapping(value="/ajaxConferencePerson",produces= "application/json;charset=UTF-8")
	public List ajaxConferencePerson(HttpServletRequest request,@RequestParam("pid") String pid){
		// 根据当前会议id查询到中间表中关联的项目信息
		List<ConfOfAttr> attrList = conOfAttrService.findAttrPersonByConfId(pid);
		for (int i = 0; i < attrList.size(); i++) {
			Person person = personService.getById(attrList.get(i).getPersonId());

			// set嘉宾名称
			attrList.get(i).setPersonName(person.getName());

			Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
			// set项会议名称
			attrList.get(i).setConferenceName(conf.getConferenceName());
			attrList.get(i).setConferenceWebSite(conf.getConferenceWebSite());
		}
		return attrList;
	}
	
	
	@ResponseBody
	@RequestMapping(value="/ajaxConferenceProject",produces= "application/json;charset=UTF-8")
	public List ajaxConferenceProject(HttpServletRequest request,@RequestParam("pid") String pid){
		// 根据当前会议id查询到中间表中关联的项目信息
		List<ConfOfAttr> attrList = conOfAttrService.findAttrProjectByConfId(pid);
		for (int i = 0; i < attrList.size(); i++) {
			Project project = projectService.getById(attrList.get(i).getProjectId());

			// set项目名称
			attrList.get(i).setProjectName(project.getProjectName());

			Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
			// set项会议名称
			attrList.get(i).setConferenceName(conf.getConferenceName());
			attrList.get(i).setConferenceWebSite(conf.getConferenceWebSite());
		}
		return attrList;
	}
	
	
	@ResponseBody
	@RequestMapping(value="/ajaxConferenceCustomer",produces= "application/json;charset=UTF-8")
	public List ajaxConferenceCustomer(HttpServletRequest request,@RequestParam("pid") String pid){
		// 根据当前会议id查询到中间表中关联的项目信息
		List<ConfOfAttr> attrList = conOfAttrService.findAttrCustomerByConfId(pid);

		for (int i = 0; i < attrList.size(); i++) {
			Customer customer = customerService.getById(attrList.get(i).getCustomerId());

			// set项目名称
			attrList.get(i).setCustomerName(customer.getCustomerName());

			Conference conf = conferenceService.getById(attrList.get(i).getConferenceId());
			// set项会议名称
			attrList.get(i).setConferenceName(conf.getConferenceName());
			attrList.get(i).setConferenceWebSite(conf.getConferenceWebSite());
		}
		return attrList;
	}
	
	
	/**
	 * 下载详情附件
	 */
	@RequestMapping("/download")
	@ResponseBody
	public void downloadFile(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "conferenceId", required = false) String conferenceId) {

		List<String> tagList = new ArrayList<>();
		List<List<String>> contentLists = Collections.synchronizedList(new ArrayList<List<String>>());
		tagList.add("专家ID");
		tagList.add("姓名");
		tagList.add("单位");
		tagList.add("职称");
		tagList.add("邮箱");
		tagList.add("手机");
		tagList.add("专业领域");
		tagList.add("人才类别");
		
		// 根据当前会议id查询到中间表中关联的嘉宾信息
		List<Person> attrList = conOfAttrService.queryPersonList(conferenceId);
		
		for (Person person : attrList) {
			List<String> content = new ArrayList<>();
			content.add(person.getExpertNumber()+"");
			content.add(person.getName());
			content.add(person.getUnit());
			content.add(person.getTitle());
			content.add(person.getEmail());
			content.add(person.getTell());
			content.add(person.getProfessionaField());
			if(StringUtil.isNotEmpty(person.getTalentLevel())){
				content.add(getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
			}
			contentLists.add(content);
		}
		//下载excel至服务器
		File file=ExcelUtil.writeExcel(tagList, contentLists, "conferencePersonList.xls");
		//将服务器上文件下载至本地
		try {
			ExcelUtil.downLoad(request, file, response);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
	}
	
	
	/**
	 * 把Person转换为LucenePerson
	 * @author dongli
	 * @date 2018年9月21日
	 * @param person
	 * @return
	 */
	public LucenePerson lucenePersonConversion(Person person){
		LucenePerson lp = new LucenePerson();
		try{
			//pid
			String expertId = person.getPid();
			if(expertId!=null&&!"".equals(expertId)){
				lp.setExpertId(expertId);
			}
			//专家id
			Integer expertNumber = person.getExpertNumber();
			if(expertNumber!=null&&expertNumber>0){
				lp.setExpertNumber("E"+expertNumber);
			}
			//专家来源
			Integer source = person.getSource();
			if(source!=null&&source>0){
				lp.setSource(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
			}
			//专家类型
			Integer type = person.getType();
			if(type!=null && type>0){
				lp.setType(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
			}
			/**
			 * 所属领域
			 */
			String researchField = person.getResearchField();
			if(researchField!=null &&!"".equals(researchField)){
				researchField = getDicCheckboxWorth(person.getResearchFieldInteger().toString(), Constant.DICTIONTRY_PROJECTFIELD);
				String[] arr  = researchField.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setResearchField(list);
			}
			//地区
			String	area =person.getArea();
			if(area!=null&&!"".equals(area)){
				lp.setArea(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
			}
			/**
			 * 人才级别
			 */
			String	talentLevel =person.getTalentLevel();
			if(talentLevel!=null&&!"".equals(talentLevel)){
				talentLevel = getDicCheckboxWorth(person.getTalentLevelInteger().toString(), Constant.DICTIONTRY_TALENTLEVEL);
				String[] arr  = talentLevel.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setTalentLevel(list);
			}
			//姓名
			String	name = person.getName();
			if(name!=null&&!"".equals(name)){
				lp.setName(name);
			}
			//毕业院校及所学专业
			String	schoolAndMajor =person.getSchoolAndMajor();
			if(schoolAndMajor!=null&&!"".equals(schoolAndMajor)){
				lp.setSchoolAndMajor(schoolAndMajor);
			}
			//单位
			String	unit = person.getUnit();
			if(unit!=null&&!"".equals(unit)){
				lp.setUnit(unit);
			}
			//职务(职称)
			String	title = person.getTitle();
			if(title!=null&&!"".equals(title)){
				lp.setTitle(title);
			}
			//专业领域
			String	professionaField =person.getProfessionaField();
			if(professionaField!=null&&!"".equals(professionaField)){
				lp.setProfessionaField(professionaField);
			}
			//教育背景
			String	education =person.getEducation();
			if(education!=null&&!"".equals(education)){
				lp.setEducation(education);
			}
			//工作经历
			String	workExp =person.getWorkExp();
			if(workExp!=null&&!"".equals(workExp)){
				lp.setWorkExp(workExp);
			}
			//荣誉奖励
			String	honorAward =person.getHonorAward();
			if(honorAward!=null&&!"".equals(honorAward)){
				lp.setHonorAward(honorAward);
			}
			//科技成果
			String	technica = person.getTechnica();
			if(technica!=null&&!"".equals(technica)){
				lp.setTechnica(technica);
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return lp;
	}

}
